//
//  CZComposeView.swift
//  WeiBo
//
//  Created by Apple on 16/9/7.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import pop

//  撰写蒙层
class CZComposeView: UIView {

    //  目标控制器
    var target: UIViewController?
    
    // MARK:    --懒加载控件
    //  模糊背景色
    private lazy var bgImageView: UIImageView = UIImageView(image: UIImage.screenShotImage().applyLightEffect())
    //  标语
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
    //  记录当前添加的菜单按钮
    private lazy var composeMenuButtonArray = [CZComposeButton]()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 获取当前屏幕的截图
//    private func screenShotImage() -> UIImage {
//        
//        //  获取当前window
//        let window = UIApplication.shared.keyWindow!
//        
//        UIGraphicsBeginImageContext(window.size)
//        //  高效的渲染方法
//        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
//        let image = UIGraphicsGetImageFromCurrentImageContext()
//        
//        UIGraphicsEndImageContext()
//        return image!
//        
//    }
    
    private func setupUI() {
        backgroundColor = RandomColor()
        
        
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self).offset(UIEdgeInsets.zero)
        }
        sloganImageView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        addChildButton()
        
        
        
    }
    
    
    //  读取plist数据
    private func composeMenuArr() -> [CZComposeMenu] {
        //  plist文件路径
        let path = Bundle.main.path(forResource: "compose", ofType: "plist")!
        //  通过NSArray读取数据
        let array = NSArray(contentsOfFile: path)!
        
        var composeMenuArray = [CZComposeMenu]()
        for dic in array {
            
            let composeMenu = CZComposeMenu(dic: dic as! [String : Any])
            composeMenuArray.append(composeMenu)
            
        }
        return composeMenuArray
    }
    
    //  添加子按钮通用方法
    private func addChildButton() {
        
        
        //  每项的宽度
        let itemWidth: CGFloat = 80
        //  每项的高度
        let itemHeight: CGFloat = 110
        
        //  每项之间的间距
        let itemMargin: CGFloat = (width - 3 * itemWidth) / 4
       
        let composeMenuArray = composeMenuArr()
        //  遍历撰写菜单模型
        for (i, composeMenu) in composeMenuArray.enumerated() {
            
            let button = CZComposeButton()
            //  设置tag标记
            button.tag = i
            button.addTarget(self, action: #selector(btnAction(button:)), for: .touchUpInside)
            button.setImage(UIImage(named: composeMenu.icon!), for: .normal)
            button.setTitle(composeMenu.title, for: .normal)
            button.size = CGSize(width: itemWidth, height: itemHeight)
            //  列的索引
            let colIndex = i % 3
            //  行的索引
            let rowIndex = i / 3
            
            button.x = itemWidth * CGFloat(colIndex) + CGFloat(colIndex + 1) * itemMargin
            button.y = itemHeight * CGFloat(rowIndex) + CGFloat(rowIndex) * itemMargin + ScreenHeight
            
            
            addSubview(button)
            
        
            composeMenuButtonArray.append(button)
        }
        
        
    }
    
    // MARK:    --点击按钮事件
    @objc private func btnAction(button: UIButton) {
        
        UIView.animate(withDuration: 0.25, animations: { 
            
            for composeMenuButton in self.composeMenuButtonArray {
                //  透明度
                composeMenuButton.alpha = 0.2
                //  判断是否相同
                if composeMenuButton == button {
                    //  放大
                    composeMenuButton.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    //  缩小
                    composeMenuButton.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            
            
            
            }) { (_) in
                
                UIView.animate(withDuration: 0.25, animations: { 
                    
                    for composeMenuButton in self.composeMenuButtonArray {
                        composeMenuButton.alpha = 1
                        composeMenuButton.transform = CGAffineTransform.identity
                    }
                    
                    }, completion: { (_) in
                        
                        let composeMenuArray = self.composeMenuArr()
                        //  通过tag获取点击的模型
                        let composeMenu = composeMenuArray[button.tag]
                        
                        //  获取对象的对象
                        
                        let vcClass = NSClassFromString(composeMenu.className!) as! UIViewController.Type
                        //  创建控制器对象
                        let vc = vcClass.init()
                        let nav = CZNavigationViewController(rootViewController: vc)
                        //  弹出控制器
                        self.target?.present(nav, animated: true, completion: {
                            //  移除当前视图
                            self.removeFromSuperview()
                        })
                        
                        
                })
                
                
        }
        
        
        
    }
    
    
    //  开启弹簧动画
    private func startAnimation(isPullup: Bool) {
    
        var menuArray = composeMenuButtonArray
        
        if isPullup == false {
            //  数组翻转
            menuArray = menuArray.reversed()
        }
        
        
        for (i, composeMenuButton) in menuArray.enumerated() {
            
            
            
            // 给每一个按钮添加一个pop动画
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //  移动到那里, 把结构体转对象
            if isPullup {
                animation?.toValue = NSValue(cgPoint: CGPoint(x: composeMenuButton.centerX, y: composeMenuButton.centerY - 350))
            } else {
                animation?.toValue = NSValue(cgPoint: CGPoint(x: composeMenuButton.centerX, y: composeMenuButton.centerY + 350))
            }
            //  弹簧速度
            animation?.springSpeed = 8
            //  弹簧幅度
            animation?.springBounciness = 10
            //  获取当前的绝对时间
            animation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            //  添加动画
            composeMenuButton.pop_add(animation, forKey: nil)
        }
        
    }
    
    
    
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //  倒序执行动画
        startAnimation(isPullup: false)
        
        //  延时0.3秒执行移除
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.removeFromSuperview()
        }
        
     
    }
    
    //  显示视图
    func show(target: UIViewController) -> Void {
        self.target = target
        //  把当前视图添加到视图控制器中
        target.view.addSubview(self)
        //  开启动画
        startAnimation(isPullup: true)
    }

}
